<template>
  <div class="app-container">
    <el-card class="cardCont">
      <h4>模板信息</h4>
      <el-descriptions class="margin-top" :column="2" border>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">{{ $t("smsTemplate.templateCode") }}</div>
          </template>
          {{ templateData.templateCode }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">{{ $t("smsTemplate.templateName") }}</div>
          </template>
          {{ templateData.templateName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">{{ $t("smsTemplate.templateType") }}</div>
          </template>
          {{ templateData.templateType }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">{{ $t("smsTemplate.auditStatus") }}</div>
          </template>
          {{
            Dict.auditStatusDict.getEnumValue(
              templateData.auditStatus as string,
            )
          }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">{{ $t("smsTemplate.templateContent") }}</div>
          </template>
          {{ templateData.templateContent }}
        </el-descriptions-item>
      </el-descriptions>
      <h4>信息发送</h4>
      <div class="text">
        <span style="margin-right: 10px">手机号码</span>
        <el-input v-model="mobilePhone" @blur="validateMobilePhone"  style="width: 200px" placeholder="请输入手机号码"/>
        <span style="margin-right: 10px ;margin-left: 30px;">短信签名</span>
        <jmash-select
          v-model="templateData.signName"
          :placeholder="$t('smsTemplate.signNameRequired')"
          :data="Dict.signNameDict.values"
          clearable
        />
      </div>
     
      <!-- 动态表格 -->
      <el-table
            style="width: 100%"
            border
            :data="formattedParams"
          >
            <el-table-column
              prop="key"
              :label="$t('smsTemplate.key')"
              align="center"
            >
            </el-table-column>
            <el-table-column 
            :label="$t('smsTemplate.contents')" 
            align="center"
            prop="content"  
            width:="70%"  
           
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.content"
                  :placeholder="$t('smsTemplate.required')"
                   maxlength="20"
                   class="input-center"
                   show-word-limit
                   clearable
                />
              </template>
            </el-table-column>
          </el-table>
      <template  class="footer">
        <!-- 发送按钮 -->
        <el-button type="primary" @click="handleSend">
          {{ $t("smsTemplate.sending") }}
        </el-button>
        <!-- 返回按钮 -->
        <el-button type="primary" @click="routerBack" style="margin-left: 10px;">
          {{ $t("common.back") }}
        </el-button>
      </template>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import {  ref } from "vue";
import { Dict } from "@/api/sms/index";
import { useRoute, useRouter } from "vue-router";
import { routerUtil } from "jmash-core";
import { smsTemplateApi } from "@/api/sms/sms-template";
import type { SmsBasicReq, SmsTemplateModel } from "@/api/sms/sms-template/types";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";

const { t } = useI18n();

const router = useRouter();
const route = useRoute();

// 模版信息
const templateData = ref<SmsTemplateModel>({});
// 短信签名
Dict.signNameDict.useValues().then((res) => {
  // 遍历res
  res.map((item) => {
    templateData.value.signName = item.value;
  });
});
// 模板参数
const formattedParams =  ref<{ key: string; content: string }[]>([]);
const mobilePhone = ref<string>(""); // 定义 mobilePhone 变量
 // 手机号校验
const validateMobilePhone = (): boolean => {
  if (mobilePhone.value === '') {
    ElMessage.error('手机号不能为空');
    return false;
  }
  const regex = /^1[3-9]\d{9}$/;
  if (!regex.test(mobilePhone.value)) {
    ElMessage.error('手机号不合法');
    return false;
  }
  return true;
};
smsTemplateApi
  .findById({ templateId: route.query.entityKey as string })
  .then(({ data }) => {
    templateData.value = data;
    // 将 data.templateParams 数组转换为一个新的数组 paramsList。每个新数组的元素是一个对象
    const params = data.templateParams;
   const paramsList = (params || []).map(item => ({
      key: String(item),
      content: ''  // 初始化为空字符串，用于输入框
    }));
    formattedParams.value = paramsList;
  });

  function convertDataListToMap(formattedParams: Array<SmsBasicReq>) {
  // 初始化一个空的记录类型对象，用于存储转换后的键值对
  const json: Record<string, string> = {};
  // 遍历输入的格式化参数数组
  for (let i = 0; i < formattedParams.length; i++) {
    // 获取当前遍历到的项
    const item = formattedParams[i];
    // 将项的键和内容作为键值对添加到对象中
    json[item.key] = item.content;
  } 
  // 返回填充了键值对的对象
  return json;
}
  // 发送按钮
  function handleSend() {
    if (!validateMobilePhone()) {
        return;
      }
    const json: Record<string, string>= convertDataListToMap(formattedParams.value as Array<SmsBasicReq>)
    const sendParams = {
    mobilePhone: mobilePhone.value,
    smsSign:templateData.value.signName,
    templateCode: templateData.value.templateCode,
    configCode: templateData.value.configCode,
    params: json,
  };
    smsTemplateApi
    .basic(sendParams)
    .then(({ status }) => {
      if (status === 200) {
        ElMessage({
          message: t("发送成功"),
          type: "success",
        });
        routerUtil.closeTagView(route.fullPath, router, false);
      } else {
        ElMessage({
          message: t("发送失败"),
          type: "error",
        });
      }
    });
  }
// 返回上一页
function routerBack() {
  routerUtil.closeTagView(route.fullPath, router, false);
}
</script>
<style lang="scss" scoped>
.text{
  margin-bottom: 20px;
}

.footer {
  display: flex;
  justify-content: center;
  align-items: center;    
  height: 100px;         
  width: 100%;             
  padding: 10px;            
  box-sizing: border-box;   
}
::v-deep .el-table__header-wrapper th {
  background-color: #f5f7fa; 
  color: #333;
}
</style>
